$(document).ready(function(){

  $('#send').click(function(){
    var text = $('#text').val();
    var nick = $('#nick').attr('value');
    var user_indicator = $('#user_indicator').attr('value');
    var chat_key = $('#chat_key').attr('value');
    var pubKey = $('#recipient_pubkey').attr('value');
    var channel_id = $('#channel_api_params').attr('channel_id');


    // You encrypt then you run the ajax function inside encrypt's callback:
    function encryptCallback(aCipherMessage){
      var cipherMessageText = JSON.stringify(aCipherMessage);
      $.ajax({
        url: '/newMessage/',
        type: 'POST',
        data: {
          text:cipherMessageText,
          // on the other end you must process 'text' with JSON.parse(text)
          // which will give you an object to pass into decrypt(). decrypt
          // also needs a callback, which takes a plaintext arg you can then display
          nick:nick,
          user_indicator:user_indicator,
          chat_key:chat_key,
          channel_id:channel_id,
        },

        success: function(data){
          $('#center').append(data);
          $('#center').animate({scrollTop:
                                $("#center").attr("scrollHeight")}, 500);
        },

        complete: function(){

        }
      }); // end ajax()
    } // end encrypt callback

    // encrypt the message, pass in the encryptCallback
    window.mozCipher.pk.encrypt($('#text').val(),
                                $('#recipient_pubkey').attr('value'),
                                encryptCallback);
  }); // end send


  $('#text').bind('keydown',function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) { //Enter keycode
      $('#send').trigger('click');
    }
  });



  openChannel = function() {
    var token = $('#channel_api_params').attr('chat_token');
    var channel = new goog.appengine.Channel(token);
    var handler = {
      'onopen': onOpened,
      'onmessage': onMessage,
      'onerror': onError,
      'onclose': onClose
    };
    var socket = channel.open(handler);
    //socket.onopen = onOpened;
    //socket.onmessage = onMessage;
  }

  // var chat_token = $('#channel_api_params').attr('chat_token');
  // var channel = new goog.appengine.Channel(chat_token);
  // var socket = channel.open();

  onOpened = function() {
    //sendMessage('/opened');
  };

  onMessage = function(m){
	//alert(m)
	

	
    var data = JSON.parse(m.data);
    // alert(data.chat_data)
    var aCipherMessage = JSON.parse(data['chat_data']);
    // var aCipherMessage = data.content;
    // alert(aCipherMessage.content);
    // decrypt the message, pass in the decryptCallback


    //window.mozCipher.pk.decrypt(aCipherMessage,
    //                            decryptCallback);


    window.mozCipher.pk.decrypt(aCipherMessage,function (aPlainText){
	                               // alert(aPlainText)
								   // document.getElementById("center").append = aPlainText;
								  });
    // $('#center').append(data['html']);

  };
  	function decryptCallback(aCipherMessage){
	// alert(aCipherMessage)
	$('#center').append(aCipherMessage);
	$('#center').animate({scrollTop:
    $("#center").attr("scrollHeight")}, 500);
	};


  onError =  function(err){
    alert("Error = "+err.description);
  };

  onClose =  function(){
    alert("channel closed");
  };

  initialize = function() {
    openChannel();
    onMessage({data: 'connected'});
  }

setTimeout(initialize, 100);

});
